package com.doge.calcalbum.widgets

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.setPadding
import com.doge.calcalbum.R
import com.doge.calcalbum.databinding.LayoutAppToolbarBinding
import com.doge.calcalbum.utils.activity
import com.doge.calcalbum.utils.lifecycleOwner
import com.doge.calcalbum.utils.setOnClickCallback
import com.doge.calcalbum.utils.systemWindowInsetsTop

class AppToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    val binding =
        LayoutAppToolbarBinding.inflate(LayoutInflater.from(context), this)

    init {
        if (!isInEditMode) {
            lifecycleOwner?.let { lifecycleOwner ->
                systemWindowInsetsTop.observe(lifecycleOwner) {
                    binding.fitsSys.setPadding(it / 2)
                }
            }
            binding.pageBack.setOnClickCallback {
                activity?.onBackPressed()
            }
        }

        if (attrs != null) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.AppToolbar, 0, 0)
            val title = a.getText(R.styleable.AppToolbar_title)
            binding.pageTitle.text = title
            a.recycle()
        }

    }
}